package com.haidechizi.longpolling.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author wangdejun
 * @create 2021/2/22 14:26
 */
@Slf4j
public class EncryptUtils {

    private EncryptUtils() {

    }

    private static final String MD5 = "MD5";

    private static final String CHARSET_NAME = StandardCharsets.UTF_8.name();

    /**
     * MD5 加密
     */
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(MD5);
            messageDigest.reset();
            messageDigest.update(str.getBytes(CHARSET_NAME));
        } catch (NoSuchAlgorithmException e) {
            log.error("加密异常", e);
            return null;
        } catch (UnsupportedEncodingException e) {
            log.error("编码异常", e);
            return null;
        }
        byte[] byteArray = messageDigest.digest();
        StringBuilder md5StrBuff = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return md5StrBuff.toString();
    }
}
